import * as echarts from "echarts";
import styles from "./index.module.less";
import { channel_id, merchant_id } from "./store";
import { generateDates, getLastWeek } from "./utils";
import { Dayjs } from "dayjs";
export default defineComponent({
  setup(props, { expose }) {
    const echartRef = ref(null);
    const datesArray = reactive(getLastWeek());
    const indexArray: any[] = createArray([], 5);
    const dateRange = ref([
      $dayjs(datesArray[0]),
      $dayjs(datesArray[datesArray.length - 1]),
    ]);
    const brokenLine = () => {
      const maxyAxisValue = Math.max(...flatten(indexArray));
      const minyAxisValue = Math.min(...flatten(indexArray));
      let option = {
        title: {
          text: "人数",
        },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: [
            $t("table208"),
            $t("table210"),
            $t("table209"),
            $t("table211"),
            $t("table212"),
          ],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: datesArray,
          axisLabel: {
            interval: 0,
            rotate: 45,
            formatter: function (value) {
              const date = new Date(value);
              return [date.getFullYear(), date.getMonth() + 1, date.getDate()]
                .map((item) => String(item).padStart(2, "0"))
                .join("/");
            },
          },
        },
        yAxis: {
          type: "value",
          max: maxyAxisValue,
          min: minyAxisValue,
          interval: Math.ceil((maxyAxisValue - minyAxisValue) / 5),
          axisLabel: {
            formatter: (value) => value,
          },
        },
        series: [
          {
            name: $t("table208"),
            type: "line",
            data: indexArray[0],
          },
          {
            name: $t("table210"),
            type: "line",
            data: indexArray[1],
          },
          {
            name: $t("table209"),
            type: "line",
            data: indexArray[2],
          },
          {
            name: $t("table211"),
            type: "line",
            data: indexArray[3],
          },
          {
            name: $t("table212"),
            type: "line",
            data: indexArray[4],
          },
        ],
      };
      const el: any = echartRef.value || querySelector("." + styles.chart_box);
      const _this: any = echarts.init(el);
      _this.setOption(option);
      window.addEventListener("resize", () => _this.resize());
    };

    const fetchChartData = async () => {
      const res = await channelApi.chart.queryChannelChart({
        start_date: toLocalTime(dateRange.value, "YYYY-MM-DD")[0],
        end_date: toLocalTime(dateRange.value, "YYYY-MM-DD")[1],
        channel_id: !isEmptyType(channel_id.value)
          ? channel_id.value
          : undefined,
        merchant_id: !isEmptyType(merchant_id.value)
          ? merchant_id.value
          : undefined,
      });
      const { data: dataArray } = res;
      indexArray.forEach((array, arrayIndex) => {
        datesArray.forEach((date, dateIndex) => {
          array[dateIndex] = "";
        });
      });
      indexArray[0] = datesArray.map((date, index) => {
        let _new = 0;
        dataArray.forEach((dataItem) => {
          if (date === dataItem.count_date) {
            _new = dataItem.new;
          }
        });
        return _new;
      });
      indexArray[1] = datesArray.map((date, index) => {
        let _loss = 0;
        dataArray.forEach((dataItem) => {
          if (date === dataItem.count_date) {
            _loss = dataItem.loss;
          }
        });
        return _loss;
      });
      indexArray[2] = datesArray.map((date, index) => {
        let _new_summary = 0;
        dataArray.forEach((dataItem) => {
          if (date === dataItem.count_date) {
            _new_summary = dataItem.new_summary;
          }
        });
        return _new_summary;
      });
      indexArray[3] = datesArray.map((date, index) => {
        let _loss_summary = 0;
        dataArray.forEach((dataItem) => {
          if (date === dataItem.count_date) {
            _loss_summary = dataItem.loss_summary;
          }
        });
        return _loss_summary;
      });
      indexArray[4] = datesArray.map((date, index) => {
        let _total = 0;
        dataArray.forEach((dataItem) => {
          if (date === dataItem.count_date) {
            _total = dataItem.total;
          }
        });
        return _total;
      });
      brokenLine();
    };
    const initPage = () => fetchChartData();
    expose({ initPage });
    return () => (
      <>
        <div class={styles.trend_chart}>
          <div class={styles.Flex_wrap}>
            <div class={styles.flex_item}>
              <s-title style="margin-bottom: 0px;">{$t("channel21")}</s-title>
            </div>
            <div class={styles.flex_item}>
              <div class={styles.title}>{$t("table73")}：</div>
              <div>
                <a-range-picker
                  v-model:value={dateRange.value}
                  onChange={(date: Dayjs | string, dateString: string) => {
                    const array = generateDates(dateString[0], dateString[1]);
                    initObjAttr(datesArray, array);
                    fetchChartData();
                  }}
                />
              </div>
            </div>
          </div>
          <div class={styles.chart_box} ref={echartRef}></div>
        </div>
      </>
    );
  },
});
